package com.iwomy.envpro.platform.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iwomy.envpro.admin.api.feign.RemoteDeptService;
import com.iwomy.envpro.app.api.entity.AppArticleCategoryEntity;
import com.iwomy.envpro.common.core.constant.SecurityConstants;
import com.iwomy.envpro.common.core.util.R;
import com.iwomy.envpro.common.data.datascope.DataScope;
import com.iwomy.envpro.common.security.util.SecurityUtils;
import com.iwomy.envpro.platform.entity.AirFactorEntity;
import com.iwomy.envpro.platform.entity.DataTemplateEntity;
import com.iwomy.envpro.platform.exception.PlatformException;
import com.iwomy.envpro.platform.mapper.DataTemplateMapper;
import com.iwomy.envpro.platform.service.AirFactorService;
import com.iwomy.envpro.platform.service.DataTemplateService;
import org.springframework.stereotype.Service;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.iwomy.envpro.platform.entity.DataTemplateDetailsEntity;
import com.iwomy.envpro.platform.mapper.DataTemplateDetailsMapper;
import org.springframework.transaction.annotation.Transactional;
import lombok.RequiredArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 数据模板
 *
 * @author pig
 * @date 2023-09-26 14:55:07
 */
@Service
@RequiredArgsConstructor
public class DataTemplateServiceImpl extends ServiceImpl<DataTemplateMapper, DataTemplateEntity> implements DataTemplateService {
	private final DataTemplateDetailsMapper dataTemplateDetailsMapper;

	private final AirFactorService airFactorService;

	private final RemoteDeptService remoteDeptService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean saveDeep(DataTemplateEntity dataTemplate) {

		DataTemplateEntity oneByTemplateName = getOneByTemplateName(dataTemplate.getTemplateName());
		if (ObjectUtil.isNotNull(oneByTemplateName)) throw new PlatformException("模板名称已存在");


		List<DataTemplateDetailsEntity> dataTemplateDetailsList = dataTemplate.getDataTemplateDetailsList();
		dataTemplate.setAssociatedQuantity(dataTemplateDetailsList.size());
//		dataTemplate.setDeptId(SecurityUtils.getUser().getDeptId());
		baseMapper.insert(dataTemplate);
		for (DataTemplateDetailsEntity dataTemplateDetails : dataTemplateDetailsList) {
			dataTemplateDetails.setDataTemplateId(dataTemplate.getId());
			dataTemplateDetailsMapper.insert(dataTemplateDetails);
		}

		return Boolean.TRUE;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean updateDeep(DataTemplateEntity dataTemplate) {


		DataTemplateEntity oneByTemplateName = getOneByTemplateName(dataTemplate.getTemplateName());
		if (ObjectUtil.isNotNull(oneByTemplateName) && !dataTemplate.getId().equals(oneByTemplateName.getId()))
			throw new PlatformException("模板名称已存在");


		List<DataTemplateDetailsEntity> dataTemplateDetailsList = dataTemplate.getDataTemplateDetailsList();
		dataTemplate.setAssociatedQuantity(dataTemplateDetailsList.size());
		baseMapper.updateById(dataTemplate);
		DataTemplateDetailsEntity dataTemplateDetailsEntity = new DataTemplateDetailsEntity();
		dataTemplateDetailsEntity.setDataTemplateId(dataTemplate.getId());
		LambdaQueryWrapper<DataTemplateDetailsEntity> wrapper = Wrappers.lambdaQuery(dataTemplateDetailsEntity);
		dataTemplateDetailsMapper.delete(wrapper);
		for (DataTemplateDetailsEntity dataTemplateDetails : dataTemplateDetailsList) {
			if (Objects.isNull(dataTemplateDetails.getDataTemplateId())) {
				dataTemplateDetails.setDataTemplateId(dataTemplate.getId());
				dataTemplateDetailsMapper.insert(dataTemplateDetails);
			} else {
				dataTemplateDetailsMapper.updateById(dataTemplateDetails);
			}
		}
		return Boolean.TRUE;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean removeDeep(Long[] ids) {
		baseMapper.deleteBatchIds(CollUtil.toList(ids));
		dataTemplateDetailsMapper.delete(Wrappers.<DataTemplateDetailsEntity>lambdaQuery().in(DataTemplateDetailsEntity::getDataTemplateId, ids));
		return Boolean.TRUE;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean removeChild(Long[] ids) {
		dataTemplateDetailsMapper.deleteBatchIds(CollUtil.toList(ids));
		return Boolean.TRUE;
	}

	@Override
	public DataTemplateEntity getOneByTemplateName(String templateName) {
		DataTemplateEntity dataTemplateEntity = new DataTemplateEntity();
		dataTemplateEntity.setTemplateName(templateName);
		LambdaQueryWrapper<DataTemplateEntity> wrapper = Wrappers.lambdaQuery(dataTemplateEntity);
		return getOne(wrapper);
	}

	@Override
	public List<AirFactorEntity> factorDetailList(DataTemplateEntity DataTemplateEntity) {

		DataTemplateEntity oneDeep = this.getOneDeep(Wrappers.query(DataTemplateEntity));
		List<Long> factorIdList = oneDeep.getDataTemplateDetailsList().stream().map(DataTemplateDetailsEntity::getFactorId).collect(Collectors.toList());
		LambdaQueryWrapper<AirFactorEntity> wrapper = Wrappers.lambdaQuery();
		wrapper.in(AirFactorEntity::getId, factorIdList);
		return airFactorService.list(wrapper);
	}

	@Override
	public Page pageByScope(Page page, DataTemplateEntity dataTemplate) {
		List data = remoteDeptService
				.listByDeptId(ObjectUtil.isNull(dataTemplate.getDeptId())? SecurityUtils.getUser().getDeptId() :dataTemplate.getDeptId()).getData();
		dataTemplate.setDeptId(null);
		LambdaQueryWrapper<DataTemplateEntity> wrapper = Wrappers.lambdaQuery(dataTemplate);
		wrapper.in(ObjectUtil.isNotEmpty(data), DataTemplateEntity::getDeptId, data);
		Page<DataTemplateEntity> dataTemplateEntityPage = this.getBaseMapper().selectPageByScope(page, wrapper, new DataScope());
		dataTemplateEntityPage.getRecords().stream().forEach(dataTemplateEntity -> {
			DataTemplateDetailsEntity dataTemplateDetailsEntity = new DataTemplateDetailsEntity();
			dataTemplateDetailsEntity.setDataTemplateId(dataTemplateEntity.getId());
			List<DataTemplateDetailsEntity> dataTemplateDetailsEntities = dataTemplateDetailsMapper.selectList(Wrappers.lambdaQuery(dataTemplateDetailsEntity));
			dataTemplateEntity.setDataTemplateDetailsList(dataTemplateDetailsEntities);
		});
		return dataTemplateEntityPage;
	}

	@Override
	public List<DataTemplateEntity> listByScope(DataTemplateEntity DataTemplateEntity) {
		List<DataTemplateEntity> dataTemplateEntities = this.getBaseMapper().selectListByScope(Wrappers.lambdaQuery(DataTemplateEntity), new DataScope());
		dataTemplateEntities.stream().forEach(dataTemplateEntity -> {
			DataTemplateDetailsEntity dataTemplateDetailsEntity = new DataTemplateDetailsEntity();
			dataTemplateDetailsEntity.setDataTemplateId(dataTemplateEntity.getId());
			List<DataTemplateDetailsEntity> dataTemplateDetailsEntities = dataTemplateDetailsMapper.selectList(Wrappers.lambdaQuery(dataTemplateDetailsEntity));
			dataTemplateEntity.setDataTemplateDetailsList(dataTemplateDetailsEntities);
		});
		return dataTemplateEntities;
	}

	@Override
	public List<DataTemplateEntity> listByDeptId(Long deptId) {
		LambdaQueryWrapper<DataTemplateEntity> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.eq(DataTemplateEntity::getDeptId, deptId);
		return this.list(queryWrapper);
	}
}